package gnss

import (
	"dgo/goutils/utils"
	"fmt"
	"math"
)

/**
码偏差
  msgid:1059(GPS), 1065(GLO)
*/

type IgmasSsrCodebiasSat struct {
	Satid uint8

	// Code Bias for specified Signal
	// 0~31
	SigMap [31]float32 // DF383 Code Bias, ±81.91 m 0.01 m
}

func (this *IgmasSsrCodebiasSat) String() string {
	var sb utils.BytesBuilder
	for i := 0; i < len(this.SigMap); i++ {
		if this.SigMap[i] != 0 {
			if sb.Len() > 0 {
				sb.AppendStr(",")
			}
			sb.Appendf("%.2d:%.2f", i+1, this.SigMap[i])
		}
	}
	return fmt.Sprintf("SatId:%d, %s", this.Satid, sb.String())
}

func EncodeIgmasSsrCodebias(head *IgmasSsrCorrectionHead, lst []*IgmasSsrCodebiasSat, outBuf []byte, startBitN int) (bitN int) {
	bitN = EncodeIgmasSsrHead(head, outBuf, startBitN, len(lst))

	for i := 0; i < len(lst); i++ {
		itm := lst[i]
		SetBitU8(outBuf, bitN, 6, itm.Satid)
		bitN += 6

		bitN_l := bitN
		SetBitU8(outBuf, bitN_l, 5, 0)
		bitN += 5

		sign := 0
		for j := 0; j < len(itm.SigMap); j++ {
			v := itm.SigMap[j]
			if v != 0 {
				// sigid
				SetBitU8(outBuf, bitN, 5, uint8(j+1))
				bitN += 5

				// code bias
				SetBitI32(outBuf, bitN, 14, int32(math.Round(float64(v)*100)))
				bitN += 14
				sign++
			}
		}
		SetBitU8(outBuf, bitN_l, 5, uint8(sign))
	}

	return
}

func DecodeIgmasSsrCodebias(inBuf []byte, startBitN int) (head *IgmasSsrCorrectionHead, lst []*IgmasSsrCodebiasSat, bitN int) {
	head = &IgmasSsrCorrectionHead{}
	bitN, n := DecodeIgmasSsrHead(head, inBuf, startBitN)
	lst = make([]*IgmasSsrCodebiasSat, n)
	for i := 0; i < len(lst); i++ {
		itm := &IgmasSsrCodebiasSat{}
		lst[i] = itm
		itm.Satid = GetBitU8(inBuf, bitN, 6)
		bitN += 6

		sigl := GetBitU8(inBuf, bitN, 5)
		bitN += 5
		for j := U8_0; j < sigl; j++ {
			sigid := GetBitU8(inBuf, bitN, 5)
			bitN += 5

			v := GetBitI32(inBuf, bitN, 14)
			bitN += 14
			itm.SigMap[sigid-1] = float32(float64(v) / 100)
		}
	}
	return
}
